﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ICSharpCode.TextEditor.Document;
using System.IO;
using System.Net;

namespace Läxomatic
{

    public partial class UppgiftInstans : Form
    {
        private Tabell<string> _cmntFile = new Tabell<string>();
        private Tabell<string> _cmntRow = new Tabell<string>();
        private Tabell<string> _cmntSubmit = new Tabell<string>();
        private List<string> _arrItemToolTips = new List<string>();
        private List<string> _info = new List<string>();
        private Tabell<string> _ListBoxPosts = new Tabell<string>();
        private string lastTip = "";
        //Ja, detta är den bökigaste klassen. Den hanterar varje enskild uppgift.
        //initierar allt.
        public UppgiftInstans()
        {
            _info = new Tabell<string>(Myskul.Command("SELECT su.gradeStatus,su.submitStatus,su.mandatory,t.maxpoints,u.fName,u.lName,su.points,su.id,t.name FROM user AS u JOIN student AS s ON ( s.userId = u.id) JOIN submit AS su ON (su.studentId = s.id) JOIN task AS t ON (t.id = su.taskID)  WHERE su.id ='" + Convert.ToString(SavedData.currentTask.getId()) + "';")).getRow(0);
            InitializeComponent();
            InitializeTextEditor();
            InitializeRBtns();
            InitializeLabels();
            InitializeListBox();
            checkUppgifter();

        }
        //Hämtar alla kommentarer.
        private void checkUppgifter()
        {
            string userId = new Tabell<string>(Myskul.Command("SELECT id FROM user WHERE loginname ='" + SavedData.user + "';"))[0, 0];
            string teacherId = new Tabell<string>(Myskul.Command("SELECT id FROM teacher WHERE userId ='" + userId + "';"))[0, 0];
            _cmntFile = new Tabell<string>(Myskul.Command("SELECT * FROM comment_file WHERE teacherId ='" + teacherId + "';"));
            _cmntRow = new Tabell<string>(Myskul.Command("SELECT * FROM comment_row WHERE teacherId ='" + teacherId + "';"));
            _cmntSubmit = new Tabell<string>(Myskul.Command("SELECT * FROM comment_submit WHERE authorId ='" + userId + "';"));
            checkComments(_cmntSubmit, _cmntRow, _cmntFile);
            ListToolTip.SetToolTip(btn_back, "Används för att resetta texten vid ändringar.");
        }
        //Fyller list-boxen med filer med data, tooltops med.
        private void InitializeListBox()
        {
            _ListBoxPosts = new Tabell<string>(Myskul.Command("SELECT sf.filename,sf.filenameHash,sf.id FROM submit_file AS sf JOIN submit AS s ON (s.id=sf.submitId) WHERE s.id ='" + Convert.ToString(SavedData.currentTask.getId()) + "';"));
            foreach (string x in _ListBoxPosts.getColumn(0))
            {
                if (x.Length > 17)
                    lbox_files.Items.Add(x.Remove(15) + "..");
                else
                    lbox_files.Items.Add(x);
                this._arrItemToolTips.Add(x);
            }
            if (lbox_files.Items.Count > 0)
                lbox_files.SelectedIndex = 0;
        }
        //Sätter radioknapparna till värden beroende på status av rättning
        private void InitializeRBtns()
        {
            switch (_info[0])
            {
                case "0":
                    rbtn_ejInlämnad.Checked = true;
                    break;
                case "1":
                    rbtn_klar.Checked = true;
                    break;
                case "2":
                    rbtn_kompletteras.Checked = true;
                    break;
            }
            if (_info[1] == "0")
            {
                foreach (RadioButton x in groupBox1.Controls)
                {
                    x.Enabled = false;
                }
            }
            if (rbtn_klar.Checked)
                panel10.Enabled = true;
        }
        //Sätter labels med värden för att ge info om krusen.
        private void InitializeLabels()
        {
            if (Convert.ToBoolean(_info[2]))
                lbl_mandatory.Text = "Ja";
            else
                lbl_mandatory.Text = "Nej";
            txt_points.Text = _info[3];
            setPoints();
            this.txt_points.TextChanged += new System.EventHandler(this.txt_points_TextChanged);
        }
        //Uppdaterar alla labels och infon om uppgiften.
        private void UpdateAll()
        {
            _info = new Tabell<string>(Myskul.Command("SELECT su.gradeStatus,su.submitStatus,su.mandatory,t.maxpoints,u.fName,u.lName,su.points,su.id,t.name FROM user AS u JOIN student AS s ON ( s.userId = u.id) JOIN submit AS su ON (su.studentId = s.id) JOIN task AS t ON (t.id = su.taskID)  WHERE su.id ='" + Convert.ToString(SavedData.currentTask.getId()) + "';")).getRow(0);
            UpdateLabels();
        }
        //uppdaterar labelsen
        private void UpdateLabels()
        {
            lbl_submit.Text = SubmitStatus(Convert.ToInt32(_info[1]));
            lbl_points.Text = _info[6] + "/" + _info[3];
        }
        //Initierar text-editorn ICSharp
        private void InitializeTextEditor()
        {
            string dir = Application.StartupPath;
            FileSyntaxModeProvider fsmp;
            if (Directory.Exists(dir))
            {
                fsmp = new FileSyntaxModeProvider(dir);
                HighlightingManager.Manager.AddSyntaxModeFileProvider(fsmp);
                TextEditor.SetHighlighting("C#");
            }
            this.TextEditor.ActiveTextAreaControl.SelectionManager.SelectionChanged += new System.EventHandler(this.textEditorControl1_Selectionchanged);
            this.TextEditor.ActiveTextAreaControl.TextArea.KeyDown += new KeyEventHandler(this.TextEditor_KeyDown);
        }
        //Går tillbaka till matrisen/resettar texten i texteditorn.
        private void btn_back_Click(object sender, EventArgs e)
        {
            string hash = _ListBoxPosts[lbox_files.SelectedIndex, 1];
            if (TextEditor.Text == getTextFromFile(hash))
            {
                Matrix matrix = new Matrix(SavedData.matrix.getCourse(), 0, 0, 50, 50);
                SavedData.mainPanel.Controls.Clear();
                SavedData.mainPanel.Controls.AddRange(matrix.Draw());
                this.Dispose();
            }
            else
            {
                TextEditor.Text = "";
                TextEditor.Refresh();
                TextEditor.Text = getTextFromFile(hash);
                btn_back.Text = "<-------";
            }
        }
        //Ändrar uppgifter i databasen beroende på vad som ändras hos radioknapparna
        void radioButton_CheckedChanged(object sender, EventArgs e)
        {
            RadioButton rb = sender as RadioButton;
            int status = 0;
            if (rbtn_ejInlämnad.Checked)
                status = 0;
            if (rbtn_klar.Checked)
            {
                status = 1;
                panel10.Enabled = true;
            }
            else
                panel10.Enabled = false;
            if (rbtn_kompletteras.Checked)
                status = 2;
            setPoints();

            Myskul.Command("UPDATE submit SET gradeStatus='" + Convert.ToString(status) + "' WHERE id ='" + Convert.ToString(SavedData.currentTask.getId()) + "';");
            SavedData.matrix.Refresh();
        }
        //Returnerar mer lättläst gradestatus
        private string GradeStatus(int gradeStatus)
        {
            if (gradeStatus == 0)
                return "Ej Rättad";
            if (gradeStatus == 1)
                return "Klar";
            if (gradeStatus == 2)
                return "Kompletteras";
            return "";
        }
        //Returnerar mer lättläst submitstatus
        private string SubmitStatus(int submitStatus)
        {
            if (submitStatus == 2)
                return "Inlämnad för sent";
            if (submitStatus == 1)
                return "Inlämnad i tid";
            if (submitStatus == 0)
                return "Ej inlämnad";
            return "";
        }
        //laddar enr textfiler från filservern
        private string getTextFromFile(string str)
        {
            WebClient webClient = new WebClient();
            return webClient.DownloadString("http://webbins.se/~johan.tmp/submit_files/" + str);

        }
        //Kallar på en funktion då indexet hos listboxen med valda filer ändras. Ändrar på texten i texteditorn
        private void lbox_files_SelectedIndexChanged(object sender, EventArgs e)
        {
            ListBox temp = (ListBox)sender;
            string hash = _ListBoxPosts[temp.SelectedIndex, 1];
            TextEditor.Text = "";
            TextEditor.Refresh();
            TextEditor.Text = getTextFromFile(hash);
        }
        //Ändrar på poänden då man anger ett specifikt värde för dem.
        private void txt_points_TextChanged(object sender, EventArgs e)
        {
            setPoints();
        }
        //KOntrolelrar så att de angivna poängen stämmer.
        private void setPoints()
        {
            if (rbtn_klar.Checked)
            {
                try
                {
                    int.Parse(txt_points.Text);
                }
                catch
                {
                    MessageBox.Show("Du måste ange ett heltal!");
                    txt_points.Text = _info[3];
                }
                if (Convert.ToInt32(txt_points.Text) > Convert.ToInt32(_info[3]))
                {
                    MessageBox.Show("Maxpoäng är " + _info[3]);
                    txt_points.Text = _info[3];
                }
                if (Convert.ToInt32(txt_points.Text) < 0)
                {
                    MessageBox.Show("Poängen måste vara högre än noll");
                    txt_points.Text = "0";
                }
                if (Convert.ToString(Convert.ToInt32(txt_points.Text)) != txt_points.Text)
                {
                    MessageBox.Show("Du måste ange en siffra!");
                    txt_points.Text = _info[3];
                }
                Myskul.Command("UPDATE submit SET points='" + txt_points.Text + "' WHERE id ='" + Convert.ToString(SavedData.currentTask.getId()) + "';");
            }
            else
                Myskul.Command("UPDATE submit SET points='0' WHERE id ='" + Convert.ToString(SavedData.currentTask.getId()) + "';");
            UpdateAll();
        }
        //Skpaar en instans av kommentardialogen, uppdaterar sedan kommentarer.
        private void btn_comment_Click(object sender, EventArgs e)
        {
            addComment addCmnt = null;
            if (TextEditor.ActiveTextAreaControl.SelectionManager.HasSomethingSelected)
            {
                List<ISelection> temp = TextEditor.ActiveTextAreaControl.SelectionManager.SelectionCollection;
                addCmnt = new addComment(_info[7], _ListBoxPosts[lbox_files.SelectedIndex, 2], TextEditor.ActiveTextAreaControl.SelectionManager.SelectedText, temp[0].StartPosition.Y + 1, temp[0].EndPosition.Y + 1);
            }
            else
                addCmnt = new addComment(_info[7], lbox_files.SelectedIndex);

            addCmnt.ShowDialog();
            addCmnt.Dispose();
            checkUppgifter();
            checkComments(_cmntSubmit, _cmntRow, _cmntFile);
        }
        //Kollar huruvida text är markerad.
        private void textEditorControl1_Selectionchanged(object sender, EventArgs e)
        {
            if (TextEditor.ActiveTextAreaControl.SelectionManager.HasSomethingSelected)
            {
                btn_comment.Text = "Kommentera markerad text";
                btn_comment.Size = new Size(146, 30);
            }
            else
            {
                btn_comment.Text = "Kommentera";
                btn_comment.Size = new Size(104, 30);
            }
        }
        //Refreshar om man trycker F5.
        private void TextEditor_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                btn_comment.PerformClick();
            if (e.KeyCode == Keys.Escape)
                btn_back.PerformClick();
        }
        //Visar tooltips för listboxen
        private void lbox_files_MouseMove(object sender, MouseEventArgs e)
        {
            ListBox listBox = (ListBox)sender;
            int index = listBox.IndexFromPoint(e.Location);
            if (index > -1 && index < listBox.Items.Count)
            {

                string tip = this._arrItemToolTips[index];
                if (tip != lastTip)
                {
                    ListToolTip.SetToolTip(listBox, tip);
                    lastTip = tip;
                }
            }

        }
        //Fyller i kommentarer i treeviewen med komemntarer.
        private void checkComments(Tabell<string> submit, Tabell<string> row, Tabell<string> file)
        {
            Tabell<string> submitFiles = new Tabell<string>(Myskul.Command("SELECT filename,id FROM submit_file WHERE submitId='" + _info[7] + "';"));
            tw_cmnts.CheckBoxes = false;
            tw_cmnts.Nodes.Clear();
            TreeNode CourseNode = new TreeNode(_info[8]);

            if(!new Tabell<string>(Myskul.Command("SELECT * FROM comment_submit WHERE submitId = '"+_info[6]+"';")).isEmpty())
            {
                CourseNode.Text += "(*)";
            }

            foreach (string id in submitFiles.getColumn(1))
            {
                string text = submitFiles.getColumn(0)[submitFiles.getColumn(1).IndexOf(id)];
                TreeNode temp = new TreeNode(text);

                if (_cmntFile.getColumn(1).IndexOf(id)!=-1)
	            {
                    temp.Text += "(*)";
                    temp.Tag = id;
	            }

                foreach (string RowId in row.getColumn(0))
                {
                    if (row.getColumn(1)[row.getColumn(0).IndexOf(RowId)]==id)
                    {
                        string textRow = row.getColumn(2)[row.getColumn(0).IndexOf(RowId)] + "-" + row.getColumn(3)[row.getColumn(0).IndexOf(RowId)] + "(*)";
                        TreeNode tempRow = new TreeNode(textRow);
                        tempRow.Tag = RowId;
                        temp.Nodes.Add(tempRow);
                    }
                }
                CourseNode.Nodes.Add(temp);
            }
            tw_cmnts.Nodes.Add(CourseNode);
            tw_cmnts.ExpandAll();

        }
        //Känenr av då man väljer en kommentar, och visar texten i texteditorn.
        private void tw_cmnts_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node.Level == 0)
                foreach (string str in _cmntSubmit.getColumn(0))
                {
                    if (_cmntSubmit.getColumn(5).IndexOf(_info[7]) != -1)
                    {
                        TextEditor.Text = "";
                        TextEditor.Refresh();
                        btn_back.Text = "Reset";
                    }

                    if (_cmntSubmit.getColumn(5)[_cmntSubmit.getColumn(0).IndexOf(str)] == _info[7])
                    {
                        TextEditor.Text += _cmntSubmit.getColumn(2)[_cmntSubmit.getColumn(0).IndexOf(str)] + "\n-------------------------------------------------------------------------------------------------------------------\n";
                    }
                }
            if (e.Node.Level == 1)
            {
                    if (e.Node.Text.EndsWith("(*)"))
                    {
                        TextEditor.Text = "";
                        TextEditor.Refresh();
                        btn_back.Text = "Reset";
                        List<string> Comments = new Tabell<string>(Myskul.Command("SELECT comment FROM comment_file WHERE fileId ='"+ e.Node.Tag +"';")).getColumn(0);
                        foreach (string str in Comments)
                        {
                            TextEditor.Text += str+"\n-------------------------------------------------------------------------------------------------------------------\n";
                        }
                        TextEditor.Refresh();

                    }
              
            }
            if (e.Node.Level == 2)
            {
                if (e.Node.Text.EndsWith("(*)"))
                {
                    TextEditor.Text = "";
                    TextEditor.Refresh();
                    btn_back.Text = "Reset";
                    List<string> Comments = new Tabell<string>(Myskul.Command("SELECT comment FROM comment_row WHERE id ='" + e.Node.Tag + "';")).getColumn(0);
                    foreach (string str in Comments)
                    {
                        TextEditor.Text += str + "\n-------------------------------------------------------------------------------------------------------------------\n";
                    }
                    TextEditor.Refresh();

                }

            }

            //////////////////FIXA FÖR FAEN
        }
    }
}
